<?php

namespace app\service;

use think\facade\Lang;
use Mayi\Alipay\AopClient;
use Mayi\Alipay\Request\AlipayTradePagePayRequest;
use Mayi\Alipay\Request\AlipayTradeWapPayRequest;
use Mayi\Alipay\Request\AlipayTradeQueryRequest;

/**
 * 支付宝支付服务类.
 */
class AliPayService
{
    // 配置信息
    protected $config;
    
    // AopClient实例
    protected $aop;

    /**
     * 构造函数.
     */
    public function __construct()
    {
        // 加载支付宝配置
        $this->config = config('app.zfb_pay');
        
        // 初始化AopClient
        $this->aop = new AopClient();
        $this->aop->gatewayUrl = $this->config['gatewayUrl'];
        $this->aop->appId = $this->config['app_id'];
        $this->aop->rsaPrivateKey = $this->config['merchant_private_key'];
        $this->aop->format = 'json';
        $this->aop->charset = $this->config['charset'];
        $this->aop->signType = $this->config['sign_type'];
        $this->aop->alipayrsaPublicKey = $this->config['alipay_public_key'];
    }

    /**
     * 电脑网站支付.
     *
     * @param string $outTradeNo  订单号
     * @param string $subject     订单标题
     * @param float  $totalAmount 订单金额
     * @param string $body        商品描述(可选)
     *
     * @return string HTML表单
     */
    public function pagePay($outTradeNo, $subject, $totalAmount, $body = '')
    {
        // 创建API请求
        $request = new AlipayTradePagePayRequest();
        
        // 设置回调地址
        $request->setNotifyUrl($this->config['notify_url']);
        $request->setReturnUrl($this->config['return_url']);
        
        // 构造业务参数
        $bizContent = [
            'out_trade_no' => $outTradeNo,
            'product_code' => 'FAST_INSTANT_TRADE_PAY',
            'total_amount' => $totalAmount,
            'subject' => $subject,
        ];
        
        // 添加可选参数
        if (!empty($body)) {
            $bizContent['body'] = $body;
        }
        
        $request->setBizContent(json_encode($bizContent));
        
        // 发送请求并获取表单
        return $this->aop->pageExecute($request, 'POST');
    }

    /**
     * 手机网站支付.
     *
     * @param string $outTradeNo  订单号
     * @param string $subject     订单标题
     * @param float  $totalAmount 订单金额
     * @param string $body        商品描述(可选)
     *
     * @return string 手机网站支付表单
     */
    public function wapPay($outTradeNo, $subject, $totalAmount, $body = '')
    {
        // 创建API请求
        $request = new AlipayTradeWapPayRequest();
        
        // 设置异步通知地址
        $request->setNotifyUrl($this->config['notify_url']);
        // 设置同步跳转地址
        $request->setReturnUrl($this->config['return_url']);

        // 构造业务参数
        $bizContent = [
            'out_trade_no' => $outTradeNo,
            'product_code' => 'QUICK_WAP_WAY',
            'total_amount' => $totalAmount,
            'subject' => $subject,
        ];
        
        // 添加可选参数
        if (!empty($body)) {
            $bizContent['body'] = $body;
        }

        $request->setBizContent(json_encode($bizContent));

        // 发送请求
        return $this->aop->pageExecute($request, 'GET');
    }

    /**
     * 处理异步通知.
     *
     * @return array 支付宝异步通知信息
     */
    public function handleNotify()
    {
        // 获取所有请求参数（ThinkPHP的input函数）
        $params = input();
        
        // 记录调试信息
        \think\facade\Log::info(Lang::get('alipay_callback_params') . '::', json_encode($params));
        
        if (empty($params)) {
            \think\facade\Log::info(Lang::get('alipay_callback_params_empty'));
            return ['success' => false];
        }
        
        try {
            // 验证签名
            $checkResult = $this->aop->rsaCheckV1($params, $this->config['alipay_public_key'], $this->config['charset']);
            \think\facade\Log::info(Lang::get('signature_verification_result') . '::', ['result' => $checkResult ? Lang::get('success') : Lang::get('failed')]);

            if ($checkResult) {
                // 验证成功
                if ($params['trade_status'] == 'TRADE_SUCCESS' || $params['trade_status'] == 'TRADE_FINISHED') {
                    // 支付成功
                    \think\facade\Log::info(Lang::get('payment_success_processing') . '::', [
                        'out_trade_no' => $params['out_trade_no'],
                        'trade_no' => $params['trade_no'],
                    ]);
                    
                    return [
                        'success' => true,
                        'out_trade_no' => $params['out_trade_no'],
                        'trade_no' => $params['trade_no'],
                        'total_amount' => $params['total_amount'],
                        'trade_status' => $params['trade_status'],
                    ];
                } else {
                    \think\facade\Log::info(Lang::get('payment_status_not_success') . '::', ['trade_status' => $params['trade_status']]);
                }
            } else {
                \think\facade\Log::info(Lang::get('signature_verification_failed'));
            }
        } catch (\Exception $e) {
            \think\facade\Log::error(Lang::get('alipay_callback_exception') . '::', ['message' => $e->getMessage()]);
        }

        return ['success' => false];
    }

    /**
     * 查询交易.
     *
     * @param string $outTradeNo 订单号
     *
     * @return array 查询结果
     */
    public function queryOrder($outTradeNo)
    {
        // 创建API请求
        $request = new AlipayTradeQueryRequest();
        
        // 构造业务参数
        $bizContent = [
            'out_trade_no' => $outTradeNo,
        ];
        
        $request->setBizContent(json_encode($bizContent));
        
        // 发送请求
        $result = $this->aop->execute($request);
        
        // 解析结果
        $responseNode = str_replace('.', '_', $request->getApiMethodName()) . '_response';
        
        if(!empty($result->$responseNode)) {
            $response = $result->$responseNode;
            
            if(!empty($response->code) && $response->code == '10000') {
                return [
                    'success' => true,
                    'out_trade_no' => $response->out_trade_no,
                    'trade_no' => $response->trade_no,
                    'total_amount' => $response->total_amount,
                    'trade_status' => $response->trade_status,
                ];
            }
        }
        
        return ['success' => false];
    }
}
